package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadApiService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * Author  王东剑
 * Created on 4/6/2024 AM9:45
 * Package_name com.atguigu.tingshu.album.service.impl
 * Description
 */
@Service
@Slf4j
public class FileUploadApiServiceImpl implements FileUploadApiService {
	@Autowired
	private MinioConstantProperties minioConstantProperties;
	@Autowired
	private MinioClient minioClient;

	@SneakyThrows
	@Override
	public String fileUpload(MultipartFile file) {
		// Make 'asiatrip' bucket if not exist.
		boolean found =
				minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
		if (!found) {
			// Make a new bucket called 'asiatrip'.
			minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
		} else {
			System.out.println("Bucket 'asiatrip' already exists.");
		}
		String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		String extension = FilenameUtils.getExtension(file.getOriginalFilename());
		String fullName = fileName + "." + extension;
		minioClient.putObject(PutObjectArgs
				.builder()
				.bucket(minioConstantProperties.getBucketName())
				.object(fullName)
				.stream(file.getInputStream(), file.getSize(), -1)
				.build());
		return minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fullName;
	}
}
